package com.example.onlinejudge.controller;

import com.example.onlinejudge.component.CodeInValidException;
import com.example.onlinejudge.component.ProblemNotFoundException;
import com.example.onlinejudge.mapper.ProblemMapper;
import com.example.onlinejudge.model.Answer;
import com.example.onlinejudge.model.Problem;
import com.example.onlinejudge.model.Question;
import com.example.onlinejudge.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController

public class CompileController {
    @Autowired
    private ProblemMapper problemMapper;
    @Autowired
    private TaskController taskController;
    //请求
    static class CompileRequest {
        public int id;
        public String code;
    }
    //返回的结果
    static class CompileResponse {
        //0代表没有错误
        public int error;
        public String reason;
        public String stdout;
    }
    @RequestMapping("/compile")
    public CompileResponse compile(@RequestBody CompileRequest compileRequest) throws IOException, InterruptedException {
        CompileResponse compileResponse = new CompileResponse();
        Problem problem=problemMapper.selectOne(compileRequest.id);
        if(problem==null){
            throw new ProblemNotFoundException();
        }
        //获取测试用例
        String testCode= problem.getTestCode();
        //requestCode 是用户提交的代码
        String requestCode = compileRequest.code;
        //把用户提交的代码和测试用例代码, 拼接成一个完整的代码
        String finalCode=mergeCode(requestCode,testCode);
        if(finalCode==null){
            throw new CodeInValidException();
        }
        Question question=new Question();
        question.setCode(finalCode);
        Answer answer=taskController.compileAndRun(question);
        //获取运行结果
        compileResponse.error=answer.getError();
        compileResponse.reason = answer.getReason();
        compileResponse.stdout = answer.getStdout();
        return compileResponse;
    }
    //将用户代码和测试用例拼接
    private static String mergeCode(String requestCode, String testCode){
        //找到 requestCode 中的最后一个 }拼接即可
        int pos=requestCode.lastIndexOf("}");
        if(pos==-1){
            //非法代码
            return null;
        }
        //根据这个位置进行字符串截取
        String subStr = requestCode.substring(0, pos);
        //进行拼接
        return subStr+testCode+"\n}";
    }

}
